<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/11/20
 * Time: 下午5:26
 */

namespace App\Console\Commands;

use App\Modules\Channel\Services\ChannelDailyStatService;
use App\Modules\Util;
use DB;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Log;

class UpdateSubscribeNum extends Command
{
    /**
     * 执行命令   php artisan force_user_active
     *
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'updateUserSubNum';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新强关号实际新增粉丝';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $date = date('Y-m-d', strtotime('-1 day'));
        $this->loadUserData($date);
    }

    function loadUserData($date)
    {
        $lists = ChannelDailyStatService::getList($date);
        foreach ($lists as $list) {
            $appid = $list->appid;
            try {
                $new_user_num_raw = self::getOfficialAccountFansNum($appid, $list->date, $list->date);
            } catch (\Exception $e) {

            }

            $new_subscribe_num = 0; //新增关注
            $cumulate_user_num = 0;//累计关注
            $cancel_subscribe_num = 0;//取消关注

            if (isset($new_user_num_raw['user_summary']['list'])) {
                $data = $new_user_num_raw['user_summary']['list'];
                if ($data && count($data) > 0) {
                    for ($index = 0; $index < count($data); $index++) {
                        $new_subscribe_num += $data[$index]['new_user'];
                        $cancel_subscribe_num += $data[$index]['cancel_user'];
                    }
                }
            }

            if (isset($new_user_num_raw['user_cumulate']['list']) && count($new_user_num_raw['user_cumulate']['list']) > 0) {
                $cumulate_user_num = $new_user_num_raw['user_cumulate']['list'][0]['cumulate_user'];
            }

            $list->cancel_subscribe_rate = (0 == $cumulate_user_num) ? '0%' : Util::getPersentAmount($cancel_subscribe_num, $cumulate_user_num);
            $list->new_subscribe_num = $new_subscribe_num;
            $list->total_subscribe_num = $cumulate_user_num;
            $list->cancel_subscribe_num = $cancel_subscribe_num;
            //\Log::info(json_encode($new_user_num_raw));
            $list->save();
        }
    }

    private static function getOfficialAccountFansNum($appid, $date)
    {
        $client = New Client(['base_uri' => env('MEDIA_API_BASE_URI')]);
        $response = $client->request('GET', 'get_gzh_statistics', ['query' => ['gzh_app_id' => $appid, 'from_date' => $date, 'to_date' => $date]]);
        $res = json_decode($response->getBody(), true);
        return $res['data'];
    }
}


